import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  RouterOptions
} from 'vue-router';
import store from '@/store';
import manage from './modules/manage';
import Layout from '@/layout/index.vue';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'index',
    redirect: '/manage',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
  },
  manage,
  {
    path: '/error',
    name: 'error',
    component: Layout,
    redirect: '/error/404',
    children: [
      {
        name: '404',
        path: '404',
        component: () => import('@/views/404/index.vue'),
        meta: { hidden: true },
      },
      {
        name: '403',
        path: '403',
        component: () => import('@/views/403/index.vue'),
        meta: { hidden: true },
      }
    ]
  },
  {
    path: '/:pathMatch(.*)',
    name: 'not-found',
    redirect: '/error',
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      left: 0,
      behavior: 'smooth',
    };
  },
} as RouterOptions);

// 路由未登录放行白名单
const routerNameWhiteList = ['login'];
router.beforeEach(async (to:any, from:any, next) => {
  if (!store.getters.userToken && !routerNameWhiteList.includes(to.name)) {
    await store.dispatch('user/checkLogin');
  }
  const userType = store.getters.userType;
  if (to.meta.requireAuth && !to.meta.requireAuth.includes(userType)) {
    next('/error/403');
  }
  next();
});

export default router;
